import { Injectable, Inject } from '@nestjs/common';
import * as cheerio from 'cheerio';
import axios from 'axios';
import { defaultUa } from './ua';
import xlsx from "node-xlsx";
import * as fs from "fs";
import * as path from 'path';

const excelPath = (name) => path.resolve(__dirname, "../", name);

@Injectable()
export class DownloadService {
  cookies: string[];

  // 获取收益数据
  async getEarnings() {
    console.log('getEarnings!');
    const url = `http://quotes.money.163.com/f10/zycwzb_600519.html`;

    const res = await axios.get(url, {
      headers: {
        'User-Agent': defaultUa,
      },
    });

    const $ = cheerio.load(res.data);

    const name = "净利润(扣除非经常性损益后)(万元)"
    let leftIndex = 0;

    // 找到符合条件行的索引
    $('table.table_bg001.border_box.limit_sale')
      .children('tbody')
      .children('tr')
      .each(function (i, elem) {
        if ($(this).children('td').text() === name) {
          // 找到索引
          leftIndex = i;
          console.log('索引：', $(this).children('td').text(), i);
        }
      })

      let dataArr = []; // 数据
    let dataTitle = [];// 表头
    // 获取数据table
    const dataTable = $('table.table_bg001.border_box.limit_sale.scr_table')
      .children('tbody')
      .children('tr');

    // 数据
    dataTable.eq(leftIndex + 1).children('td').each(function (i, elem) {
      dataArr[i] = $(this).text();
    })
    // 表头
    dataTable.children('th').each(function (i, elem) {
      dataTitle[i] = $(this).text();
    })
    // console.log(222, dataArr.length, dataTitle.length);

    this.exportData(name, dataTitle, dataArr)
    return;
  }

  // 导出
  exportData(name, title, data) {
    // console.log("exportData", name, title, data);

    let tableData = [];
    tableData.push(title)// 表格表头
    tableData.push(data)

    var buffer = xlsx.build([{ name: 'sheet1', data: tableData }]);
    console.log("excel", excelPath + name + '.xlsx');

    fs.writeFileSync(excelPath(name + '.xlsx'), buffer, { 'flag': 'w' });
  }
}
